home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 5215 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.5 KB

  1. Path: crl.crl.com!not-for-mail
  2. From: bobfry@crl.com (Robert Fry)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: embedded strtok() calls on different strings?
  5. Date: 8 Feb 1996 11:05:06 -0800
  6. Organization: CRL Dialup Internet Access
  7. Message-ID: <4fdhh2$1bs@crl.crl.com>
  8. References: <DMGrn7.1Bx0@CompStar.bnr.ca>
  9. NNTP-Posting-Host: crl.com
  10.  
  11. Sorry, but you're stuck. strtok() is acting exactly as defined, modifying 
  12. string1 and string2 (and you're lucky you're on a system that didn't 
  13. write-protect the strings), and losing the pointer to string1. The only 
  14. way around this is to write your own version of strtok that is able to 
  15. handle multiple sets of strings. It's not too difficult, but your 
  16. function will then work differently than the standard strtok().
  17.  
  18.   Bob
  19.  
  20. tzinck@bnr.ca  writes:
  21.  
  22. >char *string1="This is string one";
  23. >char *string2="This is string two";
  24.  
  25. >void *vp1;
  26. >void *vp2;
  27.  
  28. >vp1 = strtok(string1," ");
  29.  
  30. >while (vp1 != NULL){
  31. >    printf("Tok1 = %s\n", (char *) vp1);
  32.  
  33. >    vp2 = strtok(string2," ");
  34. >    while (vp2!=NULL){
  35. >        printf("Tok2 = %s\n", (char *) vp2);
  36. >        vp2 = strtok(NULL, " ");
  37. >    }
  38.  
  39. >    vp1 = strtok(NULL, " ");
  40. >}
  41.  
  42. >But the output is :
  43. >Tok1 = This
  44. >Tok2 = This
  45. >Tok2 = is
  46. >Tok2 = string
  47. >Tok2 = two
  48.  
  49.  
  50. >as vp1 gets corrupted. Any thoughts ?
  51.  
  52. Both string1 and stringtwo should be modified by strtok (with NULLs 
  53. inserted between your tokens). Calling strtok after the last token has 
  54. been read is an error, and undefined (it crashes on my system). This is 
  55. what would happen on my system if I tried to run your code and reached 
  56. the final call.
  57.  
  58.   Bob
  59.